// ui/device_management.go
package ui

import (
	"device_manager/models"
	"device_manager/utils"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"gorm.io/gorm"
)

func CreateDeviceManagementTab(db *gorm.DB) fyne.CanvasObject {
	devices := loadAllDevices(db)

	var deviceTable *widget.Table

	deviceTable = widget.NewTable(
		func() (int, int) { return len(devices) + 1, 5 },
		func() fyne.CanvasObject {
			return container.NewMax(widget.NewLabel(""))
		},
		func(tci widget.TableCellID, co fyne.CanvasObject) {
			container := co.(*fyne.Container)
			if tci.Row == 0 {
				label := widget.NewLabel("")
				label.Alignment = fyne.TextAlignCenter
				switch tci.Col {
				case 0:
					label.SetText("设备名称")
				case 1:
					label.SetText("设备SN")
				case 2:
					label.SetText("设备类型")
				case 3:
					label.SetText("编辑")
				case 4:
					label.SetText("删除")
				}
				container.Objects = []fyne.CanvasObject{label}
			} else {
				device := devices[tci.Row-1]
				switch tci.Col {
				case 0:
					label := widget.NewLabel(device.Name)
					label.Alignment = fyne.TextAlignCenter
					container.Objects = []fyne.CanvasObject{label}
				case 1:
					label := widget.NewLabel(device.DeviceSN)
					label.Alignment = fyne.TextAlignCenter
					container.Objects = []fyne.CanvasObject{label}
				case 2:
					label := widget.NewLabel(device.DeviceType)
					label.Alignment = fyne.TextAlignCenter
					container.Objects = []fyne.CanvasObject{label}
				case 3:
					editButton := widget.NewButton("编辑", func() {
						showDeviceForm(db, &device, func() {
							devices = loadAllDevices(db)
							deviceTable.Refresh()
						})
					})
					container.Objects = []fyne.CanvasObject{editButton}
				case 4:
					deleteButton := widget.NewButton("删除", func() {
						confirm := dialog.NewConfirm("删除设备", "确定要删除该设备吗？", func(confirmed bool) {
							if confirmed {
								err := db.Delete(&device).Error
								if err != nil {
									utils.ShowError(err)
								} else {
									utils.ShowInfo("设备已删除")
									devices = loadAllDevices(db)
									deviceTable.Refresh()
								}
							}
						}, fyne.CurrentApp().Driver().AllWindows()[0])
						confirm.Show()
					})
					container.Objects = []fyne.CanvasObject{deleteButton}
				}
			}
		},
	)

	// 设置每列的宽度
	deviceTable.SetColumnWidth(0, 150)
	deviceTable.SetColumnWidth(1, 200)
	deviceTable.SetColumnWidth(2, 100)
	deviceTable.SetColumnWidth(3, 80)
	deviceTable.SetColumnWidth(4, 80)

	addButton := widget.NewButton("添加设备", func() {
		showDeviceForm(db, nil, func() {
			devices = loadAllDevices(db)
			deviceTable.Refresh()
		})
	})

	content := container.NewBorder(
		nil,
		container.NewHBox(addButton),
		nil,
		nil,
		deviceTable,
	)

	return content
}

func showDeviceForm(db *gorm.DB, device *models.Device, onSave func()) {
	var nameEntry, snEntry *widget.Entry
	var deviceTypeSelect *widget.Select
	isNew := false

	if device == nil {
		device = &models.Device{}
		isNew = true
	}

	nameEntry = widget.NewEntry()
	nameEntry.SetText(device.Name)
	nameEntry.SetPlaceHolder("设备名称")

	snEntry = widget.NewEntry()
	snEntry.SetText(device.DeviceSN)
	snEntry.SetPlaceHolder("设备SN")

	deviceTypes := []string{"门禁", "电源空开", "云喇叭"}
	deviceTypeSelect = widget.NewSelect(deviceTypes, func(s string) {
		device.DeviceType = s
	})
	deviceTypeSelect.SetSelected(device.DeviceType)

	form := &widget.Form{
		Items: []*widget.FormItem{
			{Text: "设备名称", Widget: nameEntry},
			{Text: "设备SN", Widget: snEntry},
			{Text: "设备类型", Widget: deviceTypeSelect},
		},
		OnSubmit: func() {
			device.Name = nameEntry.Text
			device.DeviceSN = snEntry.Text
			device.DeviceType = deviceTypeSelect.Selected

			var err error
			if isNew {
				err = db.Create(device).Error
			} else {
				err = db.Save(device).Error
			}

			if err != nil {
				utils.ShowError(err)
			} else {
				utils.ShowInfo("设备已保存")
				onSave()
			}
		},
	}

	w := fyne.CurrentApp().NewWindow("设备信息")
	w.SetContent(form)
	w.Resize(fyne.NewSize(400, 300))
	w.Show()
}

func loadAllDevices(db *gorm.DB) []models.Device {
	var devices []models.Device
	db.Find(&devices)
	return devices
}
